import 'dart:async';
import 'dart:io';

import 'package:find_friend/common/alert_tool.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';

class MyNetWorkPlayer {
  AudioCache audioCache;
  AudioPlayer audioPlayer;
  String url;
  Timer _timer;
  int _audiotime = 0;
  int _audioduration = 30; // 音频时长
  Function(int second) _onPlayDuration;

  factory MyNetWorkPlayer() => _getInstance();
  static MyNetWorkPlayer get instance => _getInstance();
  static MyNetWorkPlayer _instance;
  MyNetWorkPlayer._() {
    // init
    _init();
  }
  static MyNetWorkPlayer _getInstance() {
    if(_instance == null) {
      _instance = MyNetWorkPlayer._();
    }
    return _instance;
  }

  void _init() {
    audioCache = AudioCache();
    audioPlayer = AudioPlayer(mode: PlayerMode.MEDIA_PLAYER);
    if (Platform.isIOS) {
      if (audioCache.fixedPlayer != null) {
        audioCache.fixedPlayer.startHeadlessService();
      }
      audioPlayer.startHeadlessService();
    }
  }

  void _beginTimer() {
    if(_timer != null) {
      return;
    }
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(_audiotime == _audioduration + 1) { // 加1是为了显示0秒钟回调
        _stopTimer();
      } else {
        _audiotime += 1;
        if(_onPlayDuration != null)_onPlayDuration(_audiotime);
      }
    });
  }

  _stopTimer({bool iscallback = false}) async {
    _audiotime = 0;
    if(iscallback) _onPlayDuration(_audioduration);
    _timer?.cancel();
    _timer = null;
    if(audioPlayer != null) await audioPlayer?.stop();
  }

  void play({String sender, islocal = false, int audioduration, Function(int second) onPlayDuration}) async {
    if(sender == url) {
      if(audioPlayer.state == AudioPlayerState.PLAYING) {
        pause();
      } else {
        remuse();
      }
      return;
    } else {
      if(url != null && _onPlayDuration != null) _onPlayDuration(_audioduration + 1);
    }
    
    url = sender;
    if(!islocal && sender.contains("http://")) { // 华为p30 没有https 访问不了
      url = sender.replaceFirst("http://", "https://");
    }
    _audioduration = audioduration == null ? 30 : audioduration;
    _onPlayDuration = onPlayDuration;

    if(url == null) {
      AlertTool.showToast("音频链接有误");
      return;
    }

    stop();

    // 开启播放计时
    if(_onPlayDuration != null) {
      _beginTimer();
    }

    int result = await audioPlayer.play(url, isLocal: islocal);
    if(result == 1) {
      print("success");
    } else {
      print("播放失败");
    }
  }

  void pause() {
    _timer?.cancel();
    _timer = null;
    audioPlayer.pause();
  }

  void remuse() {
    _beginTimer();
    audioPlayer.resume();
  }

  void stop({bool iscallback = false}) async {
    _stopTimer(iscallback: iscallback);
    await audioPlayer?.stop();
  }

}